//
//  CallBackVC.swift
//  d11
//
//  Created by peale_pro on 2019/10/16.
//  Copyright © 2019 Tech_001. All rights reserved.
//

import UIKit

class CallBackVC: BXBaseVC,PGDatePickerDelegate,UITableViewDelegate,UITableViewDataSource{
    let  reuseIdentifierID : String = "CallBackNumberTitleCell"
    let  reuseIdentifierID2 : String = "CallBackNumberCell"
    let  reuseIdentifierID3 : String = "CallBackNumberHintCell"
    let  reuseIdentifierID4 : String = "CallBackDateCell"
    let  reuseIdentifierID5 : String = "CallBackSeltQuestionCell"
    let  reuseIdentifierID6 : String = "CallBackDesQuestionCell"
    let  reuseIdentifierID7 : String = "CallBackSubNumberCell"
    var callBackDateCell :CallBackDateCell?
    var callBackSeltQuestion :CallBackSeltQuestionCell?
    var callBackNumberCell :CallBackNumberCell?
    var callBackSubNumberCell :CallBackSubNumberCell?
    //问题详情
    var callBackDesQuestionCell :CallBackDesQuestionCell?
    //cid的问题详情
    var cid :String?
    var scid :String?
    var dtmark :Int = 0;
    var callQuestionCategory :[Any]?
    //未经筛选的第二类数据
    var callQuestionSubCategory :[Any]?
    //当提交的时候判断是不是true 来决定第二个问题有没有值 所以刚开始的时候赋值为false
    var secTrue :Bool = false
    //回拨的电话号码(主)
    var phoneNumber :String = ""
    //回拨时间
    var callBackTime :String = ""
    lazy var tableView:UITableView = {
           let table = UITableView(frame:CGRect(x: 0, y: 0, width: self.view.width, height:kScreenHeight-kTabBarBottom-50), style:UITableView.Style.plain)
           table.dataSource = self
           table.delegate = self
           //table.layoutMargins = UIEdgeInsets.zero
           table.separatorStyle = .none
           table.backgroundColor  = UIColor.white
           table.showsVerticalScrollIndicator = false
           table.tableFooterView = UIView.init()
           table.separatorStyle = .none
           table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
           table.estimatedRowHeight = 0
           table.estimatedSectionHeaderHeight = 0
           table.estimatedSectionFooterHeight = 0
//           if #available(iOS 11.0, *) {
//               table.contentInsetAdjustmentBehavior = .never
//
//           } else {
//               self.automaticallyAdjustsScrollViewInsets = false
//           }
           return table
       }()
    var isAdd = false
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "电话回拨"
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.tableView)
        self.initSubmitBtn()
        self.getQuestionList()
        self.leftButtonActionWithImg("icon_default_back")
    }
    
    func initSubmitBtn() -> Void {
        let submitBtn  = UIButton.init(type: .custom)
        submitBtn.setTitle("提交", for: .normal)
        let layerGradient = CAGradientLayer()
        layerGradient.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradient.frame = CGRect(x: 0, y: 0, width: (kScreenWidth-60)/2, height: 40)
        submitBtn.layer.addSublayer(layerGradient)
        submitBtn.layer.cornerRadius = 5;
        submitBtn.layer.masksToBounds = true
       // submitBtn.addTarget(self, action: #selector(self.actionToDepoistSubmit), for: .touchUpInside)
        self.view.addSubview(submitBtn)
        submitBtn.snp.makeConstraints { (make) in
            make.width.equalTo((kScreenWidth-60)/2)
            make.height.equalTo(40)
            make.left.equalToSuperview().offset(20)
            make.bottom.equalToSuperview().offset(-(kTabBarBottom+10))
        }
        
        let cancel  = UIButton.init(type: .custom)
         cancel.setTitle("取消", for: .normal)
         let layerGradient2 = CAGradientLayer()
         layerGradient2.colors = [
             UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
             UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
         ]
         layerGradient2.frame = CGRect(x: 0, y: 0, width:(kScreenWidth-60)/2, height: 40)
         cancel.layer.addSublayer(layerGradient2)
         cancel.layer.cornerRadius = 5;
         cancel.layer.masksToBounds = true
         cancel.addTarget(self, action: #selector(self.canCellButton), for: .touchUpInside)
         submitBtn.addTarget(self, action: #selector(self.subCommitList), for: .touchUpInside)
         self.view.addSubview(cancel)
         cancel.snp.makeConstraints { (make) in
             make.width.equalTo((kScreenWidth-60)/2)
             make.height.equalTo(40)
             make.left.equalTo(submitBtn.snp.right).offset(20)
             make.bottom.equalToSuperview().offset(-(kTabBarBottom+10))
         }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            if isAdd == true{
                return 4
            }
            return 3
        }else{
            return 1
        }
         
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0{
            if indexPath.row == 0{
                return 40
            }else if indexPath.row == 1{
                return 45
            }else if indexPath.row == 3{
                return 45
            }else{
                return 70
            }
        }else if indexPath.section == 1 {
            return 100
        }else if indexPath.section == 2{
            return 130
        }else if indexPath.section == 3{
            return 150
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            return UIView.init()
        }
        
        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 0
        }
        
        func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
            return 0
        }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          if indexPath.section == 0{
            if indexPath.row == 0{
            var cell :CallBackNumberTitleCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID as String) as? CallBackNumberTitleCell
             if cell == nil {
                    cell =  CallBackNumberTitleCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID as String)
             }
             return cell!
            }else if indexPath.row == 1{
                self.callBackNumberCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID2 as String) as? CallBackNumberCell
                if self.callBackNumberCell == nil {
                       self.callBackNumberCell =  CallBackNumberCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID2 as String)
                }
                //numberField
                return (self.callBackNumberCell ?? UITableViewCell.init())!
            }else if indexPath.row == 2{
                var cell :CallBackNumberHintCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID3 as String) as? CallBackNumberHintCell
                if cell == nil {
                       cell =  CallBackNumberHintCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID3 as String)
                }
                cell?.callChangeBlock({
                    if(self.isAdd){
                    self.isAdd = false
                    }else{
                    self.isAdd = true
                    }
                    self.tableView.reloadData()
                })
                return cell!
            }else if indexPath.row == 3{
                self.callBackSubNumberCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID7 as String) as? CallBackSubNumberCell
                if self.callBackSubNumberCell == nil {
                       self.callBackSubNumberCell =  CallBackSubNumberCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID7 as String)
                }
                return (self.callBackSubNumberCell ?? UITableViewCell.init())!
            }
          }else if indexPath.section == 1{
            self.callBackDateCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID4 as String) as? CallBackDateCell
            if self.callBackDateCell == nil {
                   self.callBackDateCell =  CallBackDateCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID4 as String)
            }
               self.callBackDateCell?.bgBtn?.addTarget(self,action: #selector(self.ddatePicker), for: UIControl.Event.touchUpInside)
            self.callBackDateCell?.timeBgBtn?.addTarget(self, action: #selector(self.timePicker), for:  UIControl.Event.touchUpInside)
            self.callBackDateCell?.endtimeBgBtn?.addTarget(self, action: #selector(self.endTimePicker), for: UIControl.Event.touchUpInside)
            return (self.callBackDateCell ?? UITableViewCell.init())!
        }else if indexPath.section == 2{
            self.callBackSeltQuestion = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID5 as String) as? CallBackSeltQuestionCell
            if self.callBackSeltQuestion == nil {
                   self.callBackSeltQuestion =  CallBackSeltQuestionCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID5 as String)
            }
            self.callBackSeltQuestion?.bgBtn1?.addTarget(self, action: #selector(self.questionA), for: UIControl.Event.touchUpInside)
              self.callBackSeltQuestion?.bgBtn2?.addTarget(self, action: #selector(self.questionB), for: UIControl.Event.touchUpInside)
            return (self.callBackSeltQuestion ?? UITableViewCell.init())!
        }else if indexPath.section == 3{
           self.callBackDesQuestionCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID6 as String) as? CallBackDesQuestionCell
            if self.callBackDesQuestionCell == nil {
                   self.callBackDesQuestionCell =  CallBackDesQuestionCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID6 as String)
            }
            return (self.callBackDesQuestionCell ??  UITableViewCell.init())!
        }
        return UITableViewCell.init()
    }
    //MARK: -时间转时间戳函数
    func timeToTimeStamp(time: String ,inputFormatter:String) -> Double {
        let dfmatter = DateFormatter()
        //设定时间格式,这里可以设置成自己需要的格式
        dfmatter.dateFormat = inputFormatter
        let last = dfmatter.date(from: time)
        let timeStamp = last?.timeIntervalSince1970
        return timeStamp!
    }
    //提交电话信息
    @objc func subCommitList(){
       //submitPhoneCallRequest
        self.showLoadHUD(title: "读取中...")
        //获取玩家第一手机号
        let mobile = self.callBackNumberCell?.numberField?.text
       //获取玩家其他手机号
        var secondMobile = self.callBackSubNumberCell?.numberField?.text
        //获取玩家的方便回拨日期
        let callDate = self.callBackDateCell?.dateLabel?.text
      
        //获取玩家的方便回拨的时间
        var callStart :String = self.callBackDateCell?.startTimeLabel?.text ?? ""
        //获取玩家的方便回拨的结束时间
        var callEnd :String = self.callBackDateCell?.endTimeLabel?.text ?? ""
      
      
        //获取玩家的问题详情
        let issue = self.callBackDesQuestionCell?.textView?.text
        //循环第二个问题有没有值
        for scidjson in self.callQuestionSubCategory ?? [""] {
            let value = scidjson as? [String:Any] ?? [:];
            if(self.cid != nil){
                if(String(value["cid"] as? Int ?? 0)  == self.cid){
                    //有值证明第二个值必须进行选择
                    self.secTrue = true
                }
            }
        }
      
        //获取玩家的问题分类的id
        let cid = self.cid
        //判断是否填写了第一个手机号吗
        if (mobile == "") {
               self.dismissLoadHUD()
        UIHelper.alertSimpleMessage(about: "请填写（主）电话号码", withDescription: "", in: self)
            return
        }
        if(callEnd == "结束时间"){
            self.dismissLoadHUD()
            UIHelper.alertSimpleMessage(about: "请填写结束时间", withDescription: "", in: self)
            return
        }
        //开始的时间
        let startCallDateTime = callDate as! String+" "+callStart as! String
        //结束的时间
        let endCallDateTime = callDate as! String+" "+callEnd as! String
        
        //开始的时间转为时间戳
        let startCallDateTimeTemp = self.timeToTimeStamp(time: startCallDateTime,inputFormatter: "yyyy-MM-dd HH:mm:ss")
        //结束的时间转为时间戳
        let endCallDateTimeTemp = self.timeToTimeStamp(time: endCallDateTime, inputFormatter: "yyyy-MM-dd HH:mm:ss")
        if endCallDateTimeTemp - startCallDateTimeTemp <= 0 {
            self.dismissLoadHUD()
            UIHelper.alertSimpleMessage(about: "结束时间需要大于开始时间", withDescription: "", in: self)
            return
        }
        
        if(secondMobile == nil){
            secondMobile = ""
        }
//        if (secondMobile == ""||secondMobile == nil) {
//               self.dismissLoadHUD()
//            UIHelper.alertSimpleMessage(about: "请填写（备）电话号码", withDescription: "", in: self)
//            return
//        }
        if(cid == nil){
            self.dismissLoadHUD()
        UIHelper.alertSimpleMessage(about: "请选择问题的第一分类", withDescription: "", in: self)
            return
        }
        //如果没有scid的情况下 则赋值scid为0
        if(!self.secTrue){
            self.scid = "0"
        }else{
            if(self.scid == "0"){
                   self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "请选择问题的第二分类", withDescription: "", in: self)
                return
            }
        }
        //获取玩家的第二个问题分类的id
        let scid = self.scid
        if(issue == ""){
               self.dismissLoadHUD()
             UIHelper.alertSimpleMessage(about: "请简单填写问题描述", withDescription: "", in: self)
            return
        }
        //请求服务器
        NetWorkRequest(API.submitPhoneCallRequest(url: "418ef1c", ccToken: API.getCcToken(), vcToken: API.getVcToken(), mobile: mobile ?? "", secondmobile: secondMobile ?? "",cid: cid ?? "" ,scid: scid ?? "",issue: issue ?? "",callDate: callDate ?? "",callStart: callStart ?? "",callEnd: callEnd ?? ""), completion: { (responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                  self.dismissLoadHUD();
               let rdodict = responseData.dictionaryObject
                let msg = rdodict?["msg"]
                let dataDict = responseData["data"].dictionaryObject
                let response = dataDict?["response"] as? [String:Any] ?? [:]
            
                let c = response["c"] as? Int
                if(c == 0){
                     UIHelper.alertSimpleMessage(about: "提交成功!", withDescription: "", in: self)
                    let time: TimeInterval = 1.0
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                          self.canCellButton()
                    }
                 
                }else{
                      UIHelper.alertSimpleMessage(about: msg as? String ?? "", withDescription: "", in: self)
                }
            }
        },failed: {(faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
            }
        }){() -> (Void) in
            DispatchQueue.main.async {
                 self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
                // self.tableView.mj_header?.endRefreshing()
            }
        }
    }
    //返回上一级页面
   @objc func canCellButton(){
        navigationController?.popViewController(animated: true)
    }
  //时间选择器
    @objc func endTimePicker() ->Void{
        let manager = PGDatePickManager()
        manager.titleLabel.text="请选择结束时间"
        // manager.datePicker.datePickerMode = PGDatePickerModeTimeAndSecond
        let picker = manager.datePicker
        picker?.delegate = self
        picker?.datePickerMode = .timeAndSecond
        self.dtmark = 2
         picker?.language = "zh-Hans"
        manager.cancelButtonText = "取消"
        manager.confirmButtonText = "确定"
        self.present(manager, animated: false, completion: nil)
    }
    @objc func timePicker() ->Void{
        let manager = PGDatePickManager()
        manager.titleLabel.text="请选择开始时间"
        // manager.datePicker.datePickerMode = PGDatePickerModeTimeAndSecond
        let picker = manager.datePicker
        picker?.delegate = self
        picker?.datePickerMode = .timeAndSecond
         self.dtmark = 1
         picker?.language = "zh-Hans"
        manager.cancelButtonText = "取消"
        manager.confirmButtonText = "确定"
        self.present(manager, animated: false, completion: nil)
    }
 @objc  func ddatePicker() ->Void{
        let manager = PGDatePickManager()
        manager.titleLabel.text="请选择日期"
       // manager.datePicker.datePickerMode = PGDatePickerModeTimeAndSecond
        let picker = manager.datePicker
        picker?.delegate = self
        picker?.datePickerMode = .date
        picker?.language = "zh-Hans"
        self.dtmark = 0
        manager.cancelButtonText = "取消"
        manager.confirmButtonText = "确定"
        self.present(manager, animated: false, completion: nil)
    }

    //第一个问题
    @objc func questionA(){
        view.endEditing(true)
        //重置第二个问题的的参数，防止第一个问题进行了选择导致第二个问题出现错误。
         self.scid = "0";
        //申请数组，传递给控件使用
         var arrayString = [String]()
        //为了排序申请一个字典变量
        var dictString = Dictionary<String,Int>();
        //循环把scname 为value值  displayorder为key值做成一个字典数据
        print("\(self.callQuestionCategory)")
        //为数组数据进行排
       self.callQuestionCategory = self.callQuestionCategory?.sorted(by: { (d1, d2) -> Bool in
            let dict1 = d1 as? [String:Any] ?? [:]
            let dict2 = d2 as? [String:Any] ?? [:]
            return dict1["displayorder"] as? Int ?? 0 > dict2["displayorder"] as? Int ?? 0
        })
        for json  in self.callQuestionCategory ?? [""] {
            let value = json as? [String:Any] ?? [:];
            let string   = value["cname"]
             arrayString.append(string as? String ?? "")
        }
        print("\(dictString)")
       UsefulPickerView.showSingleColPicker("请选择问题", data: arrayString, defaultSelectedIndex: 0) { (selecedIndex, title) in
        self.callBackSeltQuestion?.titleLabel1?.text = title
        self.callBackSeltQuestion?.titleLabel2?.text = "--- 请选择 ---"
        for json in self.callQuestionCategory ?? [""] {
            let value = json as? [String:Any] ?? [:];
            if(value["cname"] as! String == title){
             //   self.scid = value["scid"] as? Int ?? 0
                self.cid =  String(value["cid"] as! Int)
            }
        }
        
       }
    }
  
    
    
    //第二个问题
    @objc  func questionB(){
        view.endEditing(true)
        //数组变量，问题名字的数据做成一个数组h传递给控件
        var arrayString = [String]()
        //为了排序申请一个字典变量
        var dictString = Dictionary<String,Int>();
        //为数组数据进行排
        self.callQuestionCategory = self.callQuestionCategory?.sorted(by: { (d1, d2) -> Bool in
            let dict1 = d1 as? [String:Any] ?? [:]
            let dict2 = d2 as? [String:Any] ?? [:]
            return dict1["displayorder"] as? Int ?? 0 > dict2["displayorder"] as? Int ?? 0
        })
        
        //循环把scname 为value值  displayorder为key值做成一个字典数据
        for json  in self.callQuestionSubCategory ?? [""] {
            let value = json as? [String:Any] ?? [:];
            if( String(value["cid"] as? Int ?? 0)  == self.cid ){
                let string  = value["scname"]
                arrayString.append(string as? String ?? "")
            }
        }
        //判断是否为空，如果是空，第二个问题不可以选择
        if(arrayString.count > 0){
        UsefulPickerView.showSingleColPicker("请选择问题", data: arrayString, defaultSelectedIndex: 0) { (selecedIndex, title) in
           self.callBackSeltQuestion?.titleLabel2?.text = title
            for json in self.callQuestionSubCategory ?? [""] {
                  let value = json as? [String:Any] ?? [:];
                if(value["scname"] as! String == title){
                    self.scid = String(value["scid"] as? Int ?? 0)
                }
            }
        }
       }else{
        //第二个问题没有scid的话则传递0
        self.scid = "0"
    
        }
    }
    func datePicker(_ datePicker: PGDatePicker!, didSelectDate dateComponents: DateComponents!) {
      
        let hour = dateComponents.hour! >= 10 ? "\(dateComponents.hour!)" : "0\(dateComponents.hour!)"
        let minute = dateComponents.minute! >= 10 ? "\(dateComponents.minute!)" : "0\(dateComponents.minute!)"
        let second = dateComponents.second! >= 10 ? "\(dateComponents.second!)" : "0\(dateComponents.second!)"
        //组合参数
        let hms = hour + ":" + minute + ":" + second
        if(self.dtmark == 1){
         self.callBackDateCell?.startTimeLabel?.text = hms
        }else if(self.dtmark == 2){
         self.callBackDateCell?.endTimeLabel?.text = hms
        }else if(self.dtmark == 0){
        let year = "\(dateComponents.year!)"
        let month = dateComponents.month! >= 10 ? "\(dateComponents.month!)" : "0\(dateComponents.month!)"
        let day = dateComponents.day! >= 10 ? "\(dateComponents.day!)" : "0\(dateComponents.day!)"
        let ymd = year + "-" + month + "-" + day
        self.callBackDateCell?.dateLabel?.text = ymd
        }
        //textbirth.text = year + "-" + month + "-" + day
    }
    //得到问题的列表
    func getQuestionList() ->Void{
         self.showLoadHUD(title: "读取中...")
        NetWorkRequest(API.getQuestionList(url: "8da9e6c", ccToken: API.getCcToken(), vcToken: API.getVcToken()), completion: { (responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD();
                let dataDict = responseData["data"].dictionaryObject
                let response = dataDict?["response"] as? [String:Any] ?? [:]
              
                let c = response["c"] as? Int
                if(c == 0){
                let d = response["d"] as? [String:Any] ?? [:]
                     //获取电话号
                    let phoneNumber :String = response["phoneNumber"] as? String ?? ""
                    //赋值给页面
                    self.callBackNumberCell?.numberField?.text = "\(phoneNumber)"
                    //获取第一个问题的集合
                    self.callQuestionCategory = d["callQuestionCategory"] as? [Any] ?? [""]
                    //获取第二个问题的集合
                    self.callQuestionSubCategory = d["callQuestionSubCategory"] as? [Any] ?? [""]
                    //获取用户的电话号码
                    self.phoneNumber = d["phoneNumber"] as? String ?? ""
                    //给前端页面赋值
                    self.callBackNumberCell?.numberField?.text = self.phoneNumber
                    //获取回拨的时间
                    self.callBackTime = d["csAvailablePeriod"] as? String ?? ""
                    //把回拨时间赋值给cell
                    self.callBackDateCell?.hintLabel?.text = "客服时间:"+self.callBackTime
                }else if(c == 1150){
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "服务器异常", withDescription: "", withOKButton: false)
                }
            }},failed: {(faildInfo,reCode,msg) -> (Void) in
                DispatchQueue.main.async {
                  self.dismissLoadHUD()
//                        UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                 
                  //  self.tableView.mj_header?.endRefreshing()
                }
        }){() -> (Void) in
            DispatchQueue.main.async {
               // self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
               // self.tableView.mj_header?.endRefreshing()
            }
        }
    }
    
    
}
